package com.hutao.manage.timer;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import com.alibaba.fastjson.JSONObject;
import com.hutao.manage.component.Config;
import com.hutao.manage.component.MyConfig;
import com.hutao.manage.mapper.FirstLevelMedicalMapper;
import com.hutao.manage.service.MedicalRecordService;
import com.hutao.manage.service.UploadFileService;
import com.hutao.manage.util.ExceptionUtil;
import com.hutao.manage.util.FileUtil;
import com.hutao.manage.util.HttpClientUtil;
import com.hutao.manage.util.ListUtil;
import com.hutao.manage.util.ObjectUtil;
import com.hutao.manage.util.PDFUtil;
import com.hutao.manage.util.StringUtil;
import com.hutao.manage.util.disk.DiskManageUtil;


/**
 * 定时器
 * @author lyh
 *
 */
@Configuration
@EnableScheduling
public class MyTimer {

	/*@Autowired
	private MyConfig myConfig;*/
	
	private Logger log = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private UploadFileService uploadFileService;
	
	@Autowired
	private MedicalRecordService medicalRecordService;
	
	@Autowired
	 private FirstLevelMedicalMapper firstLevelMedicalMapper;
	
	@Autowired  
    private Config conf;
	
	@Autowired
	private MyConfig myConfig;
	
	@Scheduled(cron = "0 0 1 * * ?") 
	//@Scheduled(cron = "0/6 * * * * ?")
	public void exportTime(){
		try{
			System.err.println("执行定时器");
			List<Map<String,Object>> datas = uploadFileService.getUploadVisitGuid();
			for (Map<String, Object> data : datas) {
				try{
					String visitGuid = ObjectUtil.getStringValue(data.get("visit_guid"));
					String mrId = ObjectUtil.getStringValue(data.get("mr_id"));
					Integer visitNumber = ObjectUtil.getIntegerValue(data.get("visit_number"));
					String params = "visitGuid="+visitGuid+"&mrId="+mrId+"&visitNumber="+visitNumber;
					String userJson = HttpClientUtil.doGet(myConfig.getExportProjectUrl()+"export305/remote_fetch_data_for_scan?"+params);
					
					if(userJson != null){
						JSONObject userMap =JSONObject.parseObject(userJson);
						boolean success = userMap.getBoolean("success");
						if(success){
							String filePath = myConfig.getHospitalVisitJsonPath() + StringUtil.getLocalPath(visitGuid);
							String fileName = visitGuid + ".json";
							String currentUser = "yyl";
							
							String diskName = DiskManageUtil.getDiskNameByFileName(conf.getConfigFileStorageAllDisk(), filePath + fileName);
							//写入到本地json文件
							String realFilePath = diskName + filePath.trim().substring(1);
							Map<String, Object> jsonMap = FileUtil.readLineFile(realFilePath, fileName);
							
							if (jsonMap != null) {
								Map<String, Object> examMap = (Map<String, Object>) jsonMap.get("examinationReportsInfo");
								if (examMap != null) {
									List<Map<String, Object>> examinationRecords = (List<Map<String, Object>>) examMap
											.get("examinationReportsRecords");
									
									//检验报告单结构化数据转换成pdf并转换成图片
									if (null != examinationRecords && examinationRecords.size() > 0) {
										List<List<Map<String, Object>>> lists = ListUtil.split(examinationRecords, 2);
										List<String> pdfPathList = new ArrayList<>();
										File tempfile = new File(conf.getExaminationPdfPath() + "temp/");
										if (!tempfile.exists()) {
											tempfile.mkdirs();
										}
										for (int i = 0; i < lists.size(); i++) {
											String guidStr = StringUtil.getId();
											PDFUtil.getPdfByTemplate(lists.get(i), conf.getExaminationPdfPath() + "template.pdf",
													conf.getExaminationPdfPath() + "temp/pdf" + guidStr + ".pdf");
											pdfPathList.add(conf.getExaminationPdfPath() + "temp/pdf" + guidStr + ".pdf");
										}
										
										File file = new File(conf.getUploadResourcePath() + "examination/" + visitGuid + "/");
										if (!file.exists()) {
											file.mkdirs();
										}
										List<String> pdfImageList = PDFUtil.pdf2Image(pdfPathList,
												conf.getUploadResourcePath() + "/examination/" + visitGuid + "/");
										
										medicalRecordService.addMedicalResourceExaminationForScan(pdfImageList, currentUser, visitGuid,conf.getUploadResourcePath() + "/examination/" + visitGuid + "/");
										//删除并发产生的数据
										medicalRecordService.deleteMreByGroupId(visitGuid, conf.getUploadResourcePath() + "/examination/" + visitGuid + "/");
									}
								}
								
								medicalRecordService.deleteUploadVisitGuid(visitGuid);
							}
						}
					}
				}
				catch (Exception ex) {
					log.error("-------自动提取数据异常---------" + ExceptionUtil.getStackTrace(ex));
					// TODO: handle exception
					
				}finally{
					System.err.println("休眠10S");
					Thread.sleep(1000*10);
				}

			}
		}catch (Exception e) {
			// TODO: handle exception
			log.error("-------自动提取数据异常---------" + ExceptionUtil.getStackTrace(e));
		}
	}

	
	
	
}



